var freightGrid;
/**
 * isShowAvailableAmount: 是否显示可用数量列
 * isShowActualAmount: 是否显示实收数量
 * freightListUrl: 货物列表弹出框中货物列表获取的url
 * 
 * 在外面jsp里面定义的全局变量
 * 		warehouseId: 仓库的id
 */
function showFreightListForm(isShowAvailableAmount, isShowActualAmount){
	if(isShowAvailableAmount == undefined){
		isShowAvailableAmount = true;
	}
	if(isShowActualAmount == undefined){
		isShowActualAmount = false;
	}
    // shorthand alias
    var fm = Ext.form;

    // the column model has information about grid columns
    // dataIndex maps the column to the specific data field in
    // the data store (created below)
    var cmArray = [
			    	{
			           header: '货物编码',
			           dataIndex: 'code',
			           width: 100
			        },{
			           header: '货物名称',
			           dataIndex: 'name',
			           width: 150
			        },{
			           header: '货物单价（元）',
			           dataIndex: 'value',
			           width: 90,
			           editor: new fm.TextField({
			           })
			        },{
			           header: '备注',
			           dataIndex: 'description',
			           width: 200,
			           editor: new fm.TextField({
			           })
			        },{
			           header: '库存数量',
			           dataIndex: 'balanceAmount',
			           width: 70
			        },{
			           header: i18n.freightAvailableAmount,
			           dataIndex: 'availableAmount',
			           width: 70
			        },{
			           header: i18n.freightAmount,
			           dataIndex: 'amount',
			           width: 70,
			           editor: new fm.NumberField({
			               allowBlank: false,
			               allowNegative: false
			           })
			        },{
			           header: i18n.actualAmount,
			           dataIndex: 'actualAmount',
			           width: 70,
			           editor: new fm.NumberField({
			               allowBlank: false,
			               allowNegative: false
			           })
			        }];
	if(!isShowAvailableAmount){
		cmArray.splice(4, 2);
	}			     
	if(!isShowActualAmount){
		cmArray.splice(cmArray.length - 1, 1);
	}
    var cm = new Ext.grid.ColumnModel(cmArray);

    cm.defaultSortable = true;


    // create the Data Store
    var store = new Ext.data.JsonStore({
        data: freights,
        fields: ['id', 'freightId', 'code', 'name', 'description', 'value', 'balanceAmount', 'availableAmount',
        		'amount', 'actualAmount', {name:'id', type: 'string'}, {name:'freightId', type: 'int'}, 
        		{name:'code', type: 'string'},{name:'name', type: 'string'},
        		 {name:'description', type:'string'}, {name:'value', type: 'float'},
        		{name:'balanceAmount', type: 'int'}, {name:'availableAmount', type: 'int'},
        		{name:'amount', type: 'int'}, {name:'actualAmount', type: 'int'}]
    });
    
	var onAddButtonClick = function(){
		new Best.FreightSelectPopup({
			url: freightListUrl,
			isShowAvailableAmount: isShowAvailableAmount,
			callback: function(records){
				var record;
				var newRecords = [];
				var isHave = false;
				var WarehouseOrderFreightRecord = Ext.data.Record.create([
				    {name: 'id', type:'string'},
				    {name: 'freightId', type:'string'},
				    {name: 'code', type:'string'},
				    {name: 'name', type:'string'},
				    {name: 'value', type:'float'},
				    {name: 'description', type:'string'},
				    {name: 'balanceAmount', type:'int'},
				    {name: 'availableAmount', type:'int'},
				    {name: 'actualAmount', type:'int'}
				]);
				for(var i=0; i<records.length; i++){
					record = records[i];
					isHave = false;
					store.each(
						function(r){
							if(record.get('code') == r.get('code')){
								isHave = true;
							}
						});
					if(!isHave){
						var newRecord = new WarehouseOrderFreightRecord({});
						newRecord.set('id', null);
						newRecord.set('freightId', record.get('id'));
						newRecord.set('code', record.get('code'));
						newRecord.set('name', record.get('name'));
						newRecord.set('value', record.get('value'));
						newRecord.set('description', record.get('description'));
						newRecord.set('balanceAmount', record.get('balanceAmount'));
						newRecord.set('availableAmount', record.get('availableAmount'));
						if(isShowActualAmount){
							newRecord.set('amount', 0);
						}else{
							if(record.get('balanceAmount') >= 1){
								newRecord.set('amount', 0);
							}else{
								if(isShowAvailableAmount){
									newRecord.set('amount', 0);
								}else{
									newRecord.set('amount', 0);
								}
							}
						}
						if(isShowActualAmount){
							newRecord.set('actualAmount', 0);
						}
						
						newRecords.push(newRecord);
					}
				}
				store.add(newRecords);
				updateFreights(store);
				freightGrid.startEditing(store.getCount() - 1, freightGrid.colModel.getColumnCount() - 1);
			}
		});
	}
	var onDeleteButtonClick = function(){
		var selection = freightGrid.getSelectionModel().selection;
		if(selection != null){
			var record = selection.record;
			if(record != undefined){
				store.remove(record);
				updateFreights(store);
			}
		}else{
			alert('请选择需要删除的货物。');
		}
	}
	var width = 780;
    if(!isShowAvailableAmount){
    	width -= 140;
    }
    if(isShowActualAmount){
    	width += 80;
    }
    var validateeditEventHandle = function(event){
    	var editor = event.grid.colModel.getCellEditor(event.column, event.row);
    	var record = event.record;
    	var value = editor.getValue();
    	var balanceAmount = record.get('balanceAmount');
    	var availableAmount = record.get('availableAmount');
    	if(value > balanceAmount){
    		alert(['不能超过库存数量']);
    		return false;
    	}else if(value > availableAmount){
    		alert(['警告：您输入的数量超过了可用数量']);
    		return true;
    	}else if(value <= 0){
    		alert(['数量必须大于0']);
    		return false;
    	}
    }
    var validateeditEventHandle2 = function(event){
    	var editor = event.grid.colModel.getCellEditor(event.column, event.row);
    	var value = editor.getValue();
    	if(value <= 0){
    		alert(['数量必须大于0']);
    		return false;
    	}
    }
    // create the editor grid
    freightGrid = new Ext.grid.EditorGridPanel({
        store: store,
        cm: cm,
        tbar: [	{text: '添加货物', handler: onAddButtonClick, iconCls: 'add'}, 
        		{text: '删除货物', handler: onDeleteButtonClick, iconCls: 'delete'} ],
        renderTo: 'freightList',
        width:width,
        title:'',
        frame:true,
        clicksToEdit:1,
        height:200
        //autoHeight:true
    });
    if(isShowAvailableAmount){
    	freightGrid.addListener('validateedit', validateeditEventHandle);
    }else{
    	freightGrid.addListener('validateedit', validateeditEventHandle2);
    }
    if(isShowActualAmount){
    	freightGrid.colModel.setEditable(2, false);
    }
}
function updateFreights(store){
	freights = [];
	store.each(function(record){
					freights.push(record.data);
				});
}
/**
 * 校验货物列表中数据
 */
function validateFreightListForm(){
	var storeData = freightGrid.store.data;
	for(var i=0; i<storeData.length; i++){
		if(storeData.get(i).get('amount') <= 0){
			freightGrid.startEditing(i, freightGrid.colModel.getColumnCount() - 1);
			alert(['数量必须大于0']);
			return false;
		}
	}
	return true;
}
	